var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];
if(getQueryString("priceLockedGoods")){
    var priceLockedGoods = getQueryString("priceLockedGoods");
    $(".price-locked-goods").val(priceLockedGoods);
}
function skuList(data) {
    dataSource = [];
    if(data.data && data.data.result.length > 0){
        $.each(data.data.result, function (i, field) {
            var rowData = new Array();
            rowData.push(field.skuId);//0
            rowData.push(field.skuCode);//1
            rowData.push(field.specifications);//2
            rowData.push(field.salesStatus);//3
            rowData.push(field.unitName);//4
            rowData.push(field.partsNumber);//5
            rowData.push(field.sendStatus);//6
            rowData.push(field.sendMessage);//7
            rowData.push(field.calculationPrice);//8
            rowData.push(field.sendDate);//9
            /* 审核状态 10 */
            rowData.push(field.channelAuditStatusDesc);//渠道审核状态描述
            /* 上架状态 11*/
            rowData.push(field.channelPutStatusDesc);//渠道上架状态的描述
            rowData.push(field.channelAuditStatus);
            rowData.push(field.channelAuditReason);
            dataSource.push(rowData);


        });
    }
    // 所有项目都开放
    shanRenderDataTable(dataSource);
}
function shanRenderDataTable(data) {
    var shanTable = $('#shanDataTable').dataTable();
    shanTable.fnClearTable();
    shanTable.fnDestroy();
    $("#shanDataTable").DataTable({
        "order": [[5, "desc"]],
        "autoWidth": false,
        "ordering": true,
        "searching": true,
        "paging": false,
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": true,
        "bLengthChange": true,
        "aLengthMenu": [5, 10, 25, 50],
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "没有数据",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='./loading.gif' />"
        },
        data: data,
        columnDefs: [
            {
                "visible": true,
                "targets": 0
            },
            // 商品码
            {
                "render": function (data, type, row, meta) {
                    return '<span><input class="skuId" type="checkbox" name="skuId" value = "' + row[0] + '">Code码：' + row[1] + '</span>'
                },
                "targets": 0
            },
            //规格名称
            {
                "render": function (data, type, row, meta) {
                    if (!row[2]) {
                        row[2] = '';
                    }
                    return '<span>' + row[2] + ' </span>';

                },
                "targets": 1
            },
            // 上下架状态
            {
                "render": function (data, type, row, meta) {
                    if (!row[3]) {
                        row[3] = '';
                        return '<span>' + row[3] + '</span>';
                    } else if (row[3] == 1) {
                        return '<span>' + '上架' + '</span>';
                    } else {
                        return '<span>' + '下架' + '</span>'
                    }
                },
                "targets": 2
            },
            //计量单位
            {
                "render": function (data, type, row, meta) {
                    var unit = row[4] ? row[4] : ''
                    return '<span>' + unit + '</span>'
                },
                "targets": 3
            },
            // 件装数量
            {
                "render": function (data, type, row, meta) {
                    var num = row[5]?row[5]:'';
                    return '<span>' + num + '</span>';
                },
                "targets": 4
            },
            // 审核状态
            {
                "render": function (data, type, row, meta) {
                    var checkStatus = row[10]?row[10]:'';
                    var auditstatus=""
                    if(row[12]!=""&&row[12]!=null&&row[12]!=undefined){
                        if(row[12]==30){
                            auditstatus='<span  onmouseover="mouseovers(\''+row[0]+'\')" onmouseout="mouseouts(\''+row[0]+'\')" style="color: brown;white-space: nowrap; overflow: hidden; text-overflow: ellipsis;width:95px;display:inline-block;">'+checkStatus+'</span><div  id="mouseBoxTwo'+row[0]+'" style="position:absolute;max-width: 400px; background: #fff;padding:10px;border:1px solid #ccc;display:none;right: 16px;pointer-events: none;">'+row[13]+'</div>'
                        }else {
                            auditstatus='<span>'+checkStatus+'</span>'
                        }
                    }else {
                        auditstatus='<span>'+checkStatus+'</span>'
                    }

                    return auditstatus;
                },
                "targets": 5
            },
            //上架状态
            {
                "render": function (data, type, row, meta) {
                    var shelvesStatus = row[11]?row[11]:'';
                    return '<span>'+shelvesStatus+'</span>';
                },
                "targets": 6
            },
            //  结算价
            {
                "render": function (data, type, row, meta) {
                    var finalPrice = row[8]?row[8]:'';
                    return '<span>' + finalPrice + '</span>';
                },
                "targets": 7
            },
            // 操作
            {
                "render": function (data, type, row, meta) {
                    return '<div class="list  630" onclick="goods_check(\'Code详情\',\'sku-info.html\',\'' + row[0] + '\')" style="cursor: pointer;color: #1476e5">查看详情</div>'+
                        '<div>' +
                        '<span style="margin-right: 8px;cursor: pointer;color: #1476e5" onclick="updateInformation(20,\''+row[1]+'\')">更新价格</span>'+
                        '<span style="cursor: pointer;color: #1476e5" onclick="updateInformation(10,\''+row[1]+'\')">更新信息</span>'+
                        '</div>'+
                        '<div style="cursor: pointer;color: #1476e5" onclick="updateInformation(30,\''+row[1]+'\')">更新上下架</div>'
                },
                "targets": 8
            },
        ],
    })
}
//审核状态鼠标移入
function mouseovers(skuid) {
    $('#mouseBoxTwo'+skuid+'').css({
        display: "inline"
    });
}
//审核状态鼠标移出
function mouseouts(skuid) {
    $('#mouseBoxTwo'+skuid+'').css({
        display: "none"
    });
}
// 更新消息接口
function sendSyncMessageInfo(type,skuId){
    // messageType 10：价格  20：商品信息 30：上下架
    // skuId 商品ID
    // customerId  渠道唯一标识
    var params = {
        messageType:type,
        skuCode:skuId ,
        customerId:sessionStorage.getItem("customerId")
    }
     var successCallBack = function(data){
         if(data.errorCode == 0){
             layer.msg('操作成功',{offset:'t',icon: 1})
         }else{
             layer.msg('操作失败',{offset:'t',icon: 2})
         }
    }
  return  web.doAjax(root.dockingplatform.sendSyncSkuMessage,'post',params,successCallBack,1)

}
// 变更消息操作  更新价格  更新信息  更新上下架
function updateInformation(type,skuId){
    layer.confirm('请确认同步该SKU的消息变更通知，并确保渠道可获取。', {
        btn: ['确认','取消'],//按钮
        offset:'t'
    }, function(){
        sendSyncMessageInfo(type,skuId)
    }, function(){
    });
}
function repeatSend(skuCode) {
    var customerId = sessionStorage.getItem("customerId");
    $.ajax({
        url: root.dockingplatform.toPush,
        cache: false,  //禁用缓存
        type: "POST",
        data: {
            "customerId": customerId,
            "skuCode": skuCode //code码
        },
        success: function (data) {
            showmsg("已加入重推队列！", 6);
        }
    });
}

// 提示信息
function showmsg(msg, icon) {
    layer.msg(msg, {
        icon: icon,
        time: 2000
    }, function () {
        if (icon == 6) {
            location.replace(location.href)
        }
    });
}

function sku_cha() {
    $.ajax({
        contentType: 'application/json',
        //url: root.goodsInter.goods_getSkuList,
        url: root.dockingplatform.queryChannelSkuList,
        cache: false,  //禁用缓存
        type: "POST",
        data: JSON.stringify({
            pageSize: 50,
            curPage: 1,
            customerId: sessionStorage.getItem("customerId"),
            areaId: sessionStorage.getItem("areaId"),
            spuId: sessionStorage.getItem("spuId"),
            //skuCode:      $("#skuCode").val(),
            skuCode: $("#productCode").val(), //code码
            specifications: $("#saleAttriValue").val(), //规格
            startTime: $("#creatimemin").val(),
            endTime: $("#creatimemax").val(),
            channelPutStatus:$('#channelShelvesStatus').find('option:selected').val(),//上架状态
            channelAuditStatus:$('#channelCheckStatus').find('option:selected').val(),//审核状态
            priceLockedGoods: $(".price-locked-goods").val()
        }),
        success: function (data) {
            skuList(data);
            $("#spu_all").attr("checked", false);
            totalPage  = data.data && data.data.totalPage ? data.data.totalPage:0
            $('.M-box4').pagination({
                pageCount: totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        contentType: 'application/json',
                        url: root.dockingplatform.queryChannelSkuList,
                        cache: false,  //禁用缓存
                        type: "POST",
                        data: JSON.stringify({
                            pageSize: 50,
                            curPage: api.getCurrent(),
                            customerId: sessionStorage.getItem("customerId"),
                            areaId: sessionStorage.getItem("areaId"),
                            spuId: sessionStorage.getItem("spuId"),
                            //skuCode:       $("#skuCode").val(),
                            skuCode: $("#productCode").val(),
                            saleStatus: $("#saleStatus").val(),
                            startTime: $("#creatimemin").val(),
                            endTime: $("#creatimemin").val(),
                            saleAttriValue: $("#saleAttriValue").val(),
                            channelPutStatus:$('#channelShelvesStatus').find('option:selected').val(),//上架状态
                            channelAuditStatus:$('#channelCheckStatus').find('option:selected').val(),//审核状态
                            priceLockedGoods: $(".price-locked-goods").val()
                        }),
                        success: function (data) {
                            skuList(data);
                            $("#spu_all").attr("checked", false);
                        }
                    });
                }
            });
        }
    });

}

/*表单验证特殊字符*/
function ValidateValue(textbox) {
    var IllegalString = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘’";
    var textboxvalue = textbox.value;
    var index = textboxvalue.length - 1;
    var s = textbox.value.charAt(index);
    if (IllegalString.indexOf(s) >= 0) {
        s = textboxvalue.substring(0, index);
        textbox.value = s;
        layer.msg("不能输入特殊字符");
    }
}

/*tab切换*/
jQuery.Huitab = function (tabBar, tabCon, class_name, tabEvent, i) {
    var $tab_menu = $(tabBar);
// 初始化操作
    $tab_menu.removeClass(class_name);
    $(tabBar).eq(i).addClass(class_name);
    $(tabCon).hide();
    $(tabCon).eq(i).show();
    $tab_menu.bind(tabEvent, function () {
        $tab_menu.removeClass(class_name);
        $(this).addClass(class_name);
        var index = $tab_menu.index(this);
        $(tabCon).hide();
        $(tabCon).eq(index).show()
    })
}
//获取用户信息
var localStorageParameters = web.readCookie("loginData");
var JsonObject = JSON.parse(localStorageParameters);

//上架
function sku_start(obj, id) {
    layer.confirm('确认要上架吗？', function (index) {
        var spu_data = {
            spuId: sessionStorage.getItem("spuId"),
            ids: id,
            status: 1,
            lastModifiedBy: JsonObject.user.user_ID,
            saleAreaId: sessionStorage.getItem("saleArea")
        }
        var succCallBack = function (data, status, response) {
            if (data.errorCode == 0) {
                layer.msg("上架成功有" + data.saleOn + "个商品,上架失败有" + data.saleFail + "个商品!", {
                    icon: 6,
                    time: 3000
                }, function () {
                    sku_cha();
                });
            } else {
                layer.msg(data.errorMessage, {icon: 6, time: 3000}, function () {
                    sku_cha();
                });
            }
        };
        return web.doAjax(root.goodsInter.goods_setSKUSaleStatus, 'post', spu_data, succCallBack);
    });
}

//下架
function sku_end(obj, id) {
    console.log(id);
    layer.confirm('确认要下架吗？', function (index) {
        var spu_data = {
            spuId: sessionStorage.getItem("spuId"),
            ids: id,
            status: 2,
            lastModifiedBy: JsonObject.user.user_ID,
            saleAreaId: sessionStorage.getItem("saleArea")
        }
        var succCallBack = function (data, status, response) {
            if (data.errorCode == 0) {
                layer.msg("操作成功!", {icon: 6, time: 3000}, function () {
                    sku_cha();
                });
            }
        };
        return web.doAjax(root.goodsInter.goods_setSKUSaleStatus, 'post', spu_data, succCallBack);
    });
}

var allIds = "";//批量上下架的id
function stopProp() {
    /*批量上架全选框阻止冒泡*/
    var timer = setTimeout(function () {
        var num = $("#datatable").find("tbody").find("input[type=checkbox]:checked").length;
        setBtnDis(num, $("#productSkuManage"));
        clearTimeout(timer);
    }, 200)
    window.event ? window.event.cancelBubble = true : e.stopPropagation();
}

//批量上架
function sku_up(obj) {
    layer.confirm('确认要批量上架吗？', function (index) {
        allIds = document.getElementsByClassName('skuId');
        var ids = [];
        for (var i = 0; i < allIds.length; i++) {
            console.log(allIds[i].checked)
            if (allIds[i].checked == true) {
                ids.push(allIds[i]);
            }
        }
        var idStr = "";
        for (var i = 0; i < ids.length; i++) {
            idStr += ids[i].value + ","
        }
        idStr = idStr.substring(0, idStr.length - 1);
        var spu_data = {
            spuId: sessionStorage.getItem("spuId"),
            ids: idStr,
            status: 1,
            lastModifiedBy: JsonObject.user.user_ID,
            saleAreaId: sessionStorage.getItem("saleArea")
        }
        var succCallBack = function (data, status, response) {
            if (data.errorCode == 0) {
                layer.msg("上架成功有" + data.saleOn + "个商品,上架失败有" + data.saleFail + "个商品!", {
                    icon: 6,
                    time: 3000
                }, function () {
                    sku_cha();
                });
            } else {
                layer.msg(data.errorMessage, {icon: 6, time: 3000}, function () {
                    sku_cha();
                });
            }
        };
        return web.doAjax(root.goodsInter.goods_setSKUSaleStatus, 'post', spu_data, succCallBack);
    });
}

//批量下架
function sku_down(obj) {
    layer.confirm('确认要批量下架吗？', function (index) {
        allIds = document.getElementsByClassName('skuId');
        var ids = [];
        for (var i = 0; i < allIds.length; i++) {
            console.log(allIds[i].checked);
            if (allIds[i].checked == true) {
                ids.push(allIds[i]);
            }
        }
        var idStr = "";
        for (var i = 0; i < ids.length; i++) {
            idStr += ids[i].value + ","
        }
        idStr = idStr.substring(0, idStr.length - 1);
        var spu_data = {
            spuId: sessionStorage.getItem("spuId"),
            ids: idStr,
            status: 2,
            lastModifiedBy: JsonObject.user.user_ID,
            saleAreaId: sessionStorage.getItem("saleArea")
        }
        var succCallBack = function (data, status, response) {
            if (data.errorCode == 0) {
                layer.msg("操作成功!", {icon: 6, time: 3000}, function () {
                    sku_cha();
                });
            }
        };
        return web.doAjax(root.goodsInter.goods_setSKUSaleStatus, 'post', spu_data, succCallBack);
    });
}


/*sku信息列表*/
function goods_check(title, url, sku_Id) {
    sessionStorage.removeItem("scene_lable");
    sessionStorage.removeItem("skuInfo");
    sessionStorage.removeItem("mini_order");
    sessionStorage.removeItem("order_limit_type");
    sessionStorage.removeItem("skuImgCache");
    sessionStorage.removeItem("attrObjCanch");
    var index = layer.open({
        type: 2,
        title: title,
        content: url + '?sku_Id=' + sku_Id
    });
    layer.full(index);
}

function goods_stock(title, url, sku_Id) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url + '?sku_Id=' + sku_Id
    });
    layer.full(index);
}

function goProduct(title, url, spu_Id) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url + '?spu_Id=' + spu_Idlocation
    });
    layer.full(index);
}

function setBtnDis(num, pnode) {  //如果选中项为空时，置灰相关按钮
    if (num <= 0) {
        pnode.find(".goods_edit").attr("disabled", "disabled").addClass("dis_btn");
    } else {
        pnode.find(".goods_edit").removeAttr("disabled").removeClass("dis_btn");
    }
}

function spuNameCache() {
    var spuCode = "SPU码：" + sessionStorage.getItem("spuCode");
    var spuName = "商品名称：" + sessionStorage.getItem("spuName");
    document.getElementById("spuId_title").innerHTML = spuCode;
    document.getElementById("spuName_title").innerHTML = spuName;
}
